package com.bhs.sansonglogistics.ui.order;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.SourceGoodsDataBean;
import com.bhs.sansonglogistics.bean.SourceGoodsDetailsBean;
import com.bhs.sansonglogistics.bean.event.Event;
import com.bhs.sansonglogistics.bean.event.PreemptStatus;
import com.bhs.sansonglogistics.bean.event.RefreshEvent;
import com.bhs.sansonglogistics.dialog.BottomRefuseDialog;
import com.bhs.sansonglogistics.dialog.BottomSelectDialog;
import com.bhs.sansonglogistics.dialog.BottomSelectPhoneDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.dialog.PreemptDialog;
import com.bhs.sansonglogistics.dialog.QuotationReceivedSuccessfullyDialog;
import com.bhs.sansonglogistics.dialog.QuotedPriceDialog;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity;
import com.bhs.sansonglogistics.ui.home.SourceGoodsListFragment;
import com.bhs.sansonglogistics.ui.mine.CustomerServiceActivity;
import com.bhs.sansonglogistics.utils.CountDownTimerUtils;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.StatusBarUtil;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.utils.VoiceUtils;
import com.bhs.sansonglogistics.view.SlideLockView;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 货源详情
 */
public class SourceGoodsDetailsActivity extends BaseActivity implements View.OnClickListener, NetCallBack {


    SlideLockView slideLockView;
    private ImageView mIvSlide;
    private ImageView mIvSlide2;
    private ImageView mIvSlide3;
    private ObjectAnimator objectAnimator;
    private ObjectAnimator objectAnimator2;
    private ObjectAnimator objectAnimator3;
    private TextView mTvTitle;
    private OrderDetailsReuse orderDetailsReuse;
    private TextView mTvRefuse;
    private TextView mTvQuotation;
    private int type;
    private String quoted_price;
    private int quoted_create_time;
    private SourceGoodsDetailsBean.DataDTO data;

    private TextView mTvOrderReceiving;
    private RelativeLayout mRlTitle;
    private View mVBg;
    private Button mBtnOrderReceiving;
    private final int ORDER_RECEIVING = 2;
    private String deliver_sn;
    private PreemptDialog dialog;

    @Override
    public int initLayout() {
        return R.layout.activity_source_goods_details;
    }

    @Override
    public void initView() {
        //注册监听
        EventBus.getDefault().register(this);
        deliver_sn = getIntent().getStringExtra("deliver_sn");
        boolean isSubscribe = getIntent().getBooleanExtra("subscribe", false);
        StatusBarUtil.setStatusBarDarkTheme(this, false);
        if (isSubscribe) {
            StatusBarUtil.setStatusBarColor(this, getColor(R.color.main));
        } else {
            StatusBarUtil.setStatusBarColor(this, 0xFFFF6067);
        }
        slideLockView = findViewById(R.id.slide_rail);
        mIvSlide = findViewById(R.id.iv_slide);
        mIvSlide2 = findViewById(R.id.iv_slide2);
        mIvSlide3 = findViewById(R.id.iv_slide3);
        mTvTitle = findViewById(R.id.tv_title);
        orderDetailsReuse = new OrderDetailsReuse(mActivity);
        mTvRefuse = findViewById(R.id.tv_refuse);
        mTvQuotation = findViewById(R.id.tv_quotation);
        findViewById(R.id.tv_online_customer_service).setOnClickListener(this);
        mTvRefuse.setOnClickListener(this);
        mTvQuotation.setOnClickListener(this);
        slideLockView.setOnClickListener(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            type = bundle.getInt("type");
            quoted_price = bundle.getString("quoted_price");
            quoted_create_time = bundle.getInt("quoted_create_time");
        }
        mTvOrderReceiving = findViewById(R.id.tv_order_receiving);

        mRlTitle = findViewById(R.id.rl_title);
        mVBg = findViewById(R.id.v_bg);
        if (!isSubscribe) {
            mRlTitle.setBackgroundColor(Color.parseColor("#FF6067"));
            mVBg.setBackgroundResource(R.drawable.bg_arc_red);
        }
        mBtnOrderReceiving = findViewById(R.id.btn_order_receiving);
        mBtnOrderReceiving.setOnClickListener(this);
        dialog = new PreemptDialog(this);
        dialog.setMyClickListener(new MyClickListener2() {
            @Override
            public void onClick(String id, String info) {
                dialog.dismiss();
                EventBus.getDefault().post(new RefreshEvent(2));
                if (id.equals("查看订单")) {
                    EventBus.getDefault().post(new Event(1));
                    startActivity(new Intent(mActivity, OrderDetailsActivity.class)
                            .putExtra("deliver_sn", deliver_sn));
                }
                finish();
            }
        });
    }

    @Override
    public void initData() {
        if (type == 1) {
            mTvRefuse.setVisibility(View.VISIBLE);
            mTvOrderReceiving.setVisibility(View.VISIBLE);
            mBtnOrderReceiving.setVisibility(View.VISIBLE);
            slideLockView.setVisibility(View.GONE);
        } else {
            objectAnimator = ObjectAnimator.ofFloat(mIvSlide, "alpha", 1f, 0.3f);
            objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
            objectAnimator.setDuration(1000);
            //动画延迟500ms执行
            // objectAnimator.setStartDelay(500);
            objectAnimator.start();

            objectAnimator2 = ObjectAnimator.ofFloat(mIvSlide2, "alpha", 1f, 0.3f);
            objectAnimator2.setRepeatCount(ValueAnimator.INFINITE);
            objectAnimator2.setDuration(1000);
            //动画延迟500ms执行
            objectAnimator2.setStartDelay(330);
            objectAnimator2.start();

            objectAnimator3 = ObjectAnimator.ofFloat(mIvSlide3, "alpha", 1f, 0.3f);
            objectAnimator3.setRepeatCount(ValueAnimator.INFINITE);
            objectAnimator3.setDuration(1000);
            //动画延迟500ms执行
            objectAnimator3.setStartDelay(660);
            objectAnimator3.start();
        }
        if (!TextUtils.isEmpty(quoted_price) && !quoted_price.equals("0")) {
            mTvQuotation.setText("查看报价");
        }
        networkRequest(netApi.getOrderDetails(deliver_sn), this);
        //滑动成功
        slideLockView.setCallback(new SlideLockView.Callback() {
            @Override
            public void onUnlock() {
                networkRequest(netApi.preempt(deliver_sn), SourceGoodsDetailsActivity.this, 777);
                //滑动成功，跳转
                dialog.show();
                dialog.winningOrder();
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (dialog.isWinningOrder) {
                            //要执行的任务
                            dialog.overtime();
                        }
                    }
                }, 32000);


            }
        });

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_order_receiving) {
            new XPopup.Builder(mActivity)
                    .isDestroyOnDismiss(false)
                    .asConfirm("提示", "您确定接单吗？",
                            "取消", "确定",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    networkRequest(netApi.orderReceiving(data.getOrder_info().getDeliver_sn()), SourceGoodsDetailsActivity.this, ORDER_RECEIVING);
                                }
                            }, null, false)
                    .show();
        } else if (v.getId() == R.id.tv_refuse) {
            BottomRefuseDialog dialog1 = new BottomRefuseDialog(null, this, data.getOrder_info().getDeliver_sn());
            dialog1.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(new RefreshEvent(1));
                    finish();
                }
            });
            new XPopup.Builder(mActivity)
                    .asCustom(dialog1)
                    .show();
        } else if (v.getId() == R.id.tv_quotation) {
            OrderGoodsBean orderGoodsBean = new OrderGoodsBean();
            orderGoodsBean.setQuoted_create_time(quoted_create_time);
            orderGoodsBean.setQuoted_price(quoted_price);
            orderGoodsBean.setLast_price(data.getOrder_info().getLast_price());
            orderGoodsBean.setDeliver_sn(data.getOrder_info().getDeliver_sn());
            orderGoodsBean.setCargo_mobile(data.getCargo_info().getMobile());
            orderGoodsBean.setPickup_mobile(data.getOrder_info().getPickup_mobile());
            orderGoodsBean.setPickup_address(data.getOrder_info().getPickup_address());
            orderGoodsBean.setReceive_mobile(data.getOrder_info().getReceive_mobile());
            orderGoodsBean.setReceive_address(data.getOrder_info().getReceive_address());
            QuotedPriceDialog quotedPriceDialog = new QuotedPriceDialog(null, this, orderGoodsBean);
            BasePopupView quotedPricePopupView = new XPopup.Builder(mActivity)
                    .asCustom(quotedPriceDialog)
                    .show();
            quotedPriceDialog.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    quotedPricePopupView.dismiss();
                }
            });
        } else if (v.getId() == R.id.tv_online_customer_service) {
            startActivity(new Intent(mActivity, CustomerServiceActivity.class));
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (objectAnimator != null) {
            objectAnimator.cancel();
            objectAnimator2.cancel();
            objectAnimator3.cancel();
        }
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            loadingPopupDismiss();
            SourceGoodsDetailsBean dataBean = new Gson().fromJson(json, SourceGoodsDetailsBean.class);
            if (dataBean.isStatus()) {
                String title = type == 1 ? "指派详情" : "极速详情";
                CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(mTvTitle, dataBean.getData().getOrder_info().getTimeout_time() * 1000L - System.currentTimeMillis(), title);
                mCountDownTimerUtils.start();

                data = dataBean.getData();
                orderDetailsReuse.initData(data);
                if (data.getOrder_info().getDeliver_type() == 3) {
                    mTvQuotation.setVisibility(View.VISIBLE);
                } else {
                    orderDetailsReuse.mIvSendMessage.setVisibility(View.GONE);
                    orderDetailsReuse.mIvCall.setVisibility(View.GONE);
                }
            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        } else if (requestCode == ORDER_RECEIVING) {
            BaseBean dataBean = new Gson().fromJson(json, BaseBean.class);
            if (dataBean.isStatus()) {
                VoiceUtils.orderReceiving(mActivity);
                QuotationReceivedSuccessfullyDialog confirmDialog = new QuotationReceivedSuccessfullyDialog(mActivity, 1);
                new XPopup.Builder(mActivity)
                        .asCustom(confirmDialog)
                        .show();
                confirmDialog.setMyClickListener(new MyClickListener() {
                    @Override
                    public void onClick(View v) {
                        confirmDialog.dismiss();
                        finish();
                        EventBus.getDefault().post(new RefreshEvent(1));
                        if (v.getId() == R.id.btn_check_order) {
                            EventBus.getDefault().post(new Event(1));
                            startActivity(new Intent(mActivity, OrderDetailsActivity.class)
                                    .putExtra("deliver_sn", deliver_sn));
                        }


                    }
                });
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    //抢单状态
    @Subscribe
    public void onEvent(PreemptStatus event) {
        if (event.isPreemptStatus()) {
            dialog.succeed(event.getDeliver_type());
        } else {
            dialog.failure();
        }
    }


}